import React, { PureComponent, Fragment, Component } from 'react';
import { Row, Col, Form, Button, InputNumber, Checkbox } from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './MemberSetting.less';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
const FormItem = Form.Item;
var recordVip ={}
var recordRead ={}
let i=0
@connect(({ member, loading }) => ({
  member,
  loading: loading.models.member,
}))
export default Form.create()(
	class extends PureComponent {
	state = {};

	componentDidMount() {
	    const { dispatch } = this.props;
	    dispatch({
	      type: 'member/getConfigureAssetInfo',
	    });
	  }


		renderStaticKey = () => {
			const arr = ['借阅书本数量', '早教课程折扣', '绘本折扣', '积分商品折扣'];
			return arr.map(text => (
				<div key={text} className={styles.wrap}>
					{text}
				</div>
			));
		};
		renderCheckbox = () => {
			const { getFieldDecorator } = this.props.form;
			const arr = [['1', '月卡'], ['2', '季度卡'], ['3', '半年卡'], ['4', '年卡']];
			return arr.map((cell, idx) => (
				<div key={cell[0]} className={styles.wrap}>
					<FormItem>
						{getFieldDecorator(`cardAssetSts[${idx}]`,{
							valuePropName:'checked',
							initialValue:this.initialValueData(`cardAssetSts[${idx}]`),
						})(<Checkbox/>)}
						<span>{cell[1]}</span>
					</FormItem>
				</div>
			));
		};
		click = () => {
			this.props.form.validateFields((err, values) => {
				 console.log('values', values);
				this.transformData(values);
			});
		};
		/**
		 * @param {bool} vip
		 */
		renderSingleInput = vip => {
			const { getFieldDecorator } = this.props.form;
			const arr = [
				['lendCount', '本'],
				['courseDiscount', '折'],
				['bookDiscount', '折'],
				['shopDiscount', '折'],
			];
			return arr.map((cell, idx) => (
				<div key={cell[0]} className={styles.wrap}>
					<FormItem>
						{getFieldDecorator(`${cell[0]}${vip ? '_vip' : ''}`, {
							rules: [
								{
									required: !vip && idx !== 0 ? false : true,
								},
							],
							initialValue:this.initialValueData(`${cell[0]}${vip ? '_vip' : ''}`)
						})(<InputNumber precision={1} step={0.1} disabled={!vip && idx !== 0} />)}
						<span>{cell[1]}</span>
					</FormItem>
				</div>
			));
		};
		renderMultiInput = vip => {
			const { getFieldDecorator } = this.props.form;
			const arr = ['1', '2', '3', '4'];
			return arr.map(cell => (
				<div key={cell} className={styles.wrap}>
					<FormItem>
						<Col span={8}>
							<FormItem>
								{getFieldDecorator(`originalPrice_${cell}${vip ? '_vip' : ''}`, {
									rules: [
										{
											required: true,
											validator: this.validate,
										},
									],
									initialValue:this.initialValueData(`originalPrice_${cell}${vip ? '_vip' : ''}`)
								})(<InputNumber  precision={0} />)}
							</FormItem>
						</Col>
						<Col span={5}>
							<div className={styles.yuan}>元</div> <div className={styles.jia}>续费价</div>
						</Col>
						<Col span={8}>
							<FormItem>
								{getFieldDecorator(`renewalPrice_${cell}${vip ? '_vip' : ''}`, {
									rules: [
										{
											required: true,
											validator: this.validate,
										},
									],
									initialValue:this.initialValueData(`renewalPrice_${cell}${vip ? '_vip' : ''}`)
								})(<InputNumber precision={0} />)}
							</FormItem>
						</Col>
						<Col span={1}>
							<span>元</span>
						</Col>
					</FormItem>
				</div>
			));
		};
		transformData = values => {
			const keys = Object.keys(values)
				.filter(key => key !== 'cardAssetSts')
				.sort();
			const customKeys = keys.filter(key => key.indexOf('_vip') === -1);
			const vipKeys = keys.filter(key => key.indexOf('_vip') !== -1);
			const fromDataRead = this.transformCustom(customKeys, values);
			const fromDataVIP = this.transformVIP(vipKeys, values);
			console.log('fromDataRead', fromDataRead);
			console.log('fromDataVIP', fromDataVIP);
			const params={
				fromDataVIP:fromDataVIP,
				fromDataRead:fromDataRead,
			}
			console.log('request')
			//const { dispatch } = this.props
		    this.props.dispatch({
		      type: 'member/configureAssetInfo',
		      payload: params,
		      callback: () => { 
		      	console.log('222request')
		      	this._callback()
				  }
		    });
		};

		transformCustom = (keys, values) => {
			const obj = { cardTypes: [{}, {}, {}, {}], applyUserRank: 1, };
			const vals = this.props.form.getFieldValue('cardAssetSts');
			console.log('vals', vals);
			keys.forEach((key, index) => {
				if (key.indexOf('_') !== -1) {
					const arr = key.split('_');
					obj.cardTypes[Number(arr[1] - 1)][arr[0]] = values[key];
					obj.cardTypes[Number(arr[1] - 1)].cardType = parseInt(arr[1]);
					obj.cardTypes[Number(arr[1] - 1)].cardAssetSts = vals[arr[1] -1] ? 0 : 1;
				} else {
					obj[key] = values[key];
				}
			});
			return obj;
		};

		transformVIP = (keys, values) => {
			const obj = { cardTypes: [{}, {}, {}, {}], applyUserRank: 2, };
			const vals = this.props.form.getFieldValue('cardAssetSts');
			keys.forEach((key, index) => {
				const arr = key.split('_');
				if (arr.length === 3) {
					obj.cardTypes[Number(arr[1] - 1)][arr[0]] = values[key];
					obj.cardTypes[Number(arr[1] - 1)].cardType = parseInt(arr[1]);
					obj.cardTypes[Number(arr[1] - 1)].cardAssetSts = vals[arr[1]-1] ? 0 : 1;
				} else {
					obj[arr[0]] = values[key];
				}
			});
			return obj;
		};
		validate = (rule, value, cb) => {
			const field = rule.field;
			const idx = field.split('_')[1];
			if (!value && value !== 0) {
				return cb('不能为空');
			}
			const isVip = field.indexOf('_vip') !== -1;
			if (field.indexOf('renewalPrice') !== -1) {
				const prev = this.props.form.getFieldValue(`originalPrice_${idx}${isVip ? '_vip' : ''}`);
				if (prev < value) {
					return cb('续费价格须小于等于首月价格');
				}
			} else {
				const next = this.props.form.getFieldValue(`renewalPrice_${idx}${isVip ? '_vip' : ''}`);
				if (value < next) {
					this.props.form.validateFields([`renewalPrice_${idx}${isVip ? '_vip' : ''}`], { force: true });
				}
			}
			cb();
		};
 _callback(){
	 	const { dispatch } = this.props;
	  dispatch({
	    type: 'member/getConfigureAssetInfo',
	  }); 
 }
		
		initialValueData =(inputName)=>{
		  if( JSON.stringify(recordRead) !="{}" &&recordRead!=undefined){
		  	const lendCount= recordRead.lendCount
			 const bookDiscount= recordRead.bookDiscount
			 const shopDiscout= recordRead.shopDiscout
			 const courseDiscount= recordRead.courseDiscount
		  	if(inputName==='lendCount'){
		  		return lendCount
			  }
			  if(inputName==="courseDiscount"){
			  	return courseDiscount
			  }
			  if(inputName==="bookDiscount"){
			  	return bookDiscount
			  }
			  if(inputName==="shopDiscount"){
			  	return shopDiscout
			  }
			  if(inputName ==="originalPrice_1"){
			  	return recordRead.cardTypes[0].originalPrice
			  }
			  if(inputName ==="originalPrice_2"){
			  	return recordRead.cardTypes[1].originalPrice
			  }
			  if(inputName ==="originalPrice_3"){
			  	return recordRead.cardTypes[2].originalPrice
			  }
			  if(inputName ==="originalPrice_4"){
			  	return recordRead.cardTypes[3].originalPrice
			  }
			  if(inputName ==="renewalPrice_1"){
			  	return recordRead.cardTypes[0].renewalPrice
			  }
			  if(inputName ==="renewalPrice_2"){
			  	return recordRead.cardTypes[1].renewalPrice
			  }
			  if(inputName ==="renewalPrice_3"){
			  	return recordRead.cardTypes[2].renewalPrice
			  }
			  if(inputName ==="renewalPrice_4"){
			  	return recordRead.cardTypes[3].renewalPrice
			  }	
			  if(inputName ==="cardAssetSts[0]"){
			  	if(recordRead.cardTypes[0].cardAssetSts===0){
			  		return true
			  	}  	
			  }	
			  if(inputName ==="cardAssetSts[1]"){
			  	if(recordRead.cardTypes[1].cardAssetSts===0){
			  		return true
			  	}  	
			  }	
			  if(inputName ==="cardAssetSts[2]"){
			  	if(recordRead.cardTypes[2].cardAssetSts===0){
			  		return true
			  	}  	
			  }	
			  if(inputName ==="cardAssetSts[3]"){
			  	if(recordRead.cardTypes[3].cardAssetSts===0){
			  		return true
			  	}  	
			  }	
			  
		  }
		   if(JSON.stringify(recordVip) !="{}" && recordVip!=undefined){
		  	const lendCount_vip= recordVip.lendCount
			 const courseDiscount_vip= recordVip.courseDiscount
			 const bookDiscount_vip= recordVip.bookDiscount
			 const shopDiscount_vip= recordVip.shopDiscout
		  	if(inputName==="lendCount_vip"){
			  	return lendCount_vip
			  }
			  if(inputName==="courseDiscount_vip"){
			  	return courseDiscount_vip
			  }
			  if(inputName==="bookDiscount_vip"){
			  	return bookDiscount_vip
			  }
			  if(inputName==="shopDiscount_vip"){
			  	return shopDiscount_vip
			  }
			  if(inputName ==="originalPrice_1_vip"){
			  	return recordVip.cardTypes[0].originalPrice
			  }
			  if(inputName ==="originalPrice_2_vip"){
			  	return recordVip.cardTypes[1].originalPrice
			  }
			  if(inputName ==="originalPrice_3_vip"){
			  	return recordVip.cardTypes[2].originalPrice
			  }
			  if(inputName ==="originalPrice_4_vip"){
			  	return recordVip.cardTypes[3].originalPrice
			  }
			  if(inputName ==="renewalPrice_1_vip"){
			  	return recordVip.cardTypes[0].renewalPrice
			  }
			  if(inputName ==="renewalPrice_2_vip"){
			  	return recordVip.cardTypes[1].renewalPrice
			  }
			  if(inputName ==="renewalPrice_3_vip"){
			  	return recordVip.cardTypes[2].renewalPrice
			  }
			  if(inputName ==="renewalPrice_4_vip"){
			  	return recordVip.cardTypes[3].renewalPrice
			  }
		  }

		}

		render() {
			const {member} =this.props
			const {i}=this.state
			console.log(member)
			recordVip = member.AssetInfoData.fromDataVIP
			recordRead = member.AssetInfoData.fromDataRead

			console.log(recordRead)
			return (
				<PageHeaderLayout title="">
					<div className={styles.container}>
						<Row>
							<Col span={4}>
								<div className={styles.title} />
								<div className={styles.wrap}>权益项</div>
								{this.renderStaticKey()}
								<div className={styles.wrap} />
								<div className={styles.wrap}>价格项</div>
								{this.renderCheckbox()}
							</Col>
							<Col span={10}>
								<div className={styles.title}>借阅会员</div>
								<div className={styles.wrap} />
								{this.renderSingleInput()}
								<div className={styles.wrap} />
								<div className={styles.wrap} />
								{this.renderMultiInput()}
							</Col>
							<Col span={10}>
								<div className={styles.title}>VIP会员</div>
								<div className={styles.wrap} />
								{this.renderSingleInput(true)}
								<div className={styles.wrap} />
								<div className={styles.wrap} />
								{this.renderMultiInput(true)}
							</Col>
						</Row>
						<Button type="primary" onClick={this.click} className={styles.btnmargin} >
							保存设置
						</Button>
					</div>
				</PageHeaderLayout>
			);
		}
	}
);